package com.yu.service;

import com.alibaba.fastjson.JSON;
import com.yu.domain.Product;
import com.yu.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    public HtmlParseUtil htmlParseUtil;

    //1、解析数据放入es索引中
    public Boolean parseContent(String keyword) throws IOException {
        List<Product> list = new ArrayList<>();
        System.out.println(keyword);
        list = htmlParseUtil.parseJD(keyword);
        //将数据直接放进es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("20s");

        for (int i = 0; i < list.size() ; i++) {
            bulkRequest.add(new IndexRequest("jd_goods").id(String.valueOf(i)).source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }


    //获取这些是数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword, int pageNo,int pageSize) throws IOException {
       if (pageNo<=1){
           pageNo=1;
       }
       //条件搜索
        System.out.println(keyword);
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //分页
        builder.from(pageNo);
        builder.size(pageSize);

        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title",keyword);
        builder.query(termQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
//            System.out.println(hit.getSourceAsMap());
        }
        return list;
    }


    public List<Map<String,Object>> searchHighlight(String keyword, int pageNo,int pageSize) throws IOException {
       if (pageNo<=1){
           pageNo=1;
       }
       //条件搜索
        System.out.println(keyword);
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //分页
        builder.from(pageNo);
        builder.size(pageSize);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//设置多个高亮
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);


        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title",keyword);
        builder.query(termQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
//            list.add(hit.getSourceAsMap());
//            System.out.println(hit.getSourceAsMap());
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            //解析高亮字段,将高亮字段内容替换原来没有高亮的
            if (title!=null){
                Text[] fragments = title.fragments();
                String newTitle = "";
                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                sourceAsMap.put("title",newTitle);
            }
            list.add(sourceAsMap);
        }
        return list;
    }


    public static void main(String[] args) throws IOException {
        ContentService service = new ContentService();
//        Boolean content = service.parseContent("java");
//        System.out.println(content);
//        List<Map<String, Object>> list = service.searchPage("奶粉");
        //高亮配置


    }

}
